<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Answer;
use App\Models\Data;
use App\Models\Hospital;
use App\Models\Member;
use App\Models\Problem;
use App\Models\Vote;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;

class HospitalController extends BaseController
{
    /**
     * 首页数据
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $build = Hospital::query();
        if (isset($params['type'])){
            $build->where('type', $params['type']);
        }
        $pageSize = $request->input('pageSize', 50);
        $data = $build->orderBy('num', 'desc')->paginate($pageSize);
        return $this->success($data);
    }

    public function hosAdd(Request $request)
    {
        $params = $request->all();
        if (!isset($params['type'])){
            return $this->errorCode('10001', [], 'type（是否消耗积分）参数为必传项');
        }
        $memberData = Hospital::query()
            ->where('type', $params['type'])
            ->where('name', $params['name'])->first();
        unset($params['token']);

        if ($memberData){
            throw new AppException('find_hospital_is_exist');
        }

        $result = Hospital::query()->create($params);
        return $this->success($result, '医院新增成功');
    }


    public function destroy($hospitalId, Request $request)
    {
        $memberData = Hospital::query()->where('hid', $hospitalId)->first();

        if (!$memberData){
            throw new AppException('find_hospital_is_fail');
        }

        $result = $memberData->delete();
        return $this->success($result, '删除成功');

    }


    public function update($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Hospital::query()->where('hid', $id)->first();
        if (!$data){
            throw new AppException('find_hospital_is_fail');
        }

        $result = Hospital::query()->where('hid', $id)->update($params);

        return $this->success($result, '修改成功');
    }

    public function createTag($id, Request $request)
    {
        //是否可以被投票
        $params = $request->all();
        unset($params['token']);
        $data = Hospital::query()->where('hid', $id)->first();
        if (!$data){
            throw new AppException('find_hospital_is_fail');
        }

        $result = Hospital::query()->where('hid', $id)->update([
            'status' => $params['status'],
            'tag' => $params['tag']
        ]);

        return $this->success($result, '修改成功');
    }

    /**
     * 投票给医院
     * @param $id
     * @param Request $request
     * @return array
     * @throws AppException
     */
    public function vote($id, Request $request)
    {
        $params = $request->all();
        unset($params['token']);
        $data = Hospital::query()->where('hid', $id)->first();
        if (!$data){
            throw new AppException('find_hospital_is_fail');
        }

        //插入投票明细表
        $data = $data->toArray();
        if ($data['status'] == Hospital::STATUS_FALSE){
            return $this->errorCode('10001', [], '此选项不可投票。请联系管理员');
        }


        if ($data['type'] == 1){

            //逻辑判断  单用户 单天只能给一个医院最高 500积分

            $haveBuild = Vote::query()->where('hospital_id', $id)
                ->where('member_id', $params['member_id'])
                ->whereBetween('created_at', [date('Y-m-d', time()), date('Y-m-d', time() + 60*60*24)]);
            $cyBuild = clone $haveBuild;
            if ($haveBuild->first()){
                $haveData = $cyBuild->get()->toArray();
                $score = array_column($haveData,'score');

                $allScore = array_sum($score);
                if ($allScore >= 500){
                    return $this->errorCode('10001', [], '每人每天最多赠与每个团队500积分');
                }
            }

            $score = $params['score'];
            //查看是否有足够的积分扣除
            $member = Member::query()->where('member_id', $params['member_id'])->first()->toArray();
            if ($params['score'] > $member['score']){
                return $this->errorCode('10001', [], '对不起，您的积分不足。投票失败');
            }

            //消耗积分
            $vote= Vote::query()->create(['hospital_id' => $id, 'score' => $params['score'],'is_delete' => Vote::IS_DELETE , 'member_id'=> $params['member_id']]);

            Member::query()->where('member_id', $params['member_id'])->increment('score', -$score);

        }else{
            //每日投票次数 为2票。
            $history = Vote::query()
                ->where('member_id', $params['member_id'])
                ->where('is_delete', Vote::IS_DELETE_NO)
                ->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d', strtotime('+1 day'))])
                ->count();

            if ($history >= 2){
                return $this->errorCode('10001', [], '您的免费投票次数，今日已经用完啦');
            }

            $vote= Vote::query()->create(['hospital_id' => $id,'score' => 0,  'is_delete' => Vote::IS_DELETE_NO , 'member_id'=> $params['member_id']]);

        }
        if ($vote){
            if ($data['type'] == 1){
                Hospital::query()->where('hid', $id)->increment('num', $params['score']);
            }
        }else{
            return $this->errorCode('10001', [], '投票失败');
        }

        return $this->success($vote, '投票成功');

    }









}